package top.lshaci.learning.springboot.web.controller;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lshaci.learning.springboot.web.model.BigDecimalValid;
import top.lshaci.learning.springboot.web.model.ListValid;
import top.lshaci.learning.springboot.web.model.ValidGroupDto;
import top.lshaci.learning.springboot.web.valid.Group1;
import top.lshaci.learning.springboot.web.valid.Group2;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import javax.validation.groups.Default;
import java.util.List;

/**
 * ValidController
 * <pre>
 *     List参数校验：
 *     1、在 Controller 上添加 {@link Validated} 注解
 *     2、在方法入参处添加对 {@link List} 验证的注解
 *     3、在 {@link List} 泛型处添加对像验证 {@link Valid} 注解
 *     4、在对象 {@link ListValid} 中字段上使用常规验证注解
 * </pre>
 *
 * @author liangxu
 */
@Validated
@RestController
@RequestMapping("/valid")
public class ValidController {

    @PostMapping("/list")
    public Object list(
            @RequestBody
            @NotEmpty(message = "数据不能为空")
            @Size(min = 2, max = 3, message = "数据数量应该在{min}到{max}之间")
                    List<@Valid ListValid> listValids
    ) {
        return listValids;
    }

    @PostMapping("/bigDecimal")
    public Object bigDecimal(@Valid @RequestBody BigDecimalValid decimalValid) {
        return decimalValid;
    }

    /**
     * {@link Valid} 只会验证 groups 未指定的校验注解
     *
     * @param dto
     * @return
     */
    @PostMapping("/group0")
    public Object validGroup0(@Valid @RequestBody ValidGroupDto dto) {
        return dto;
    }

    /**
     * {@link Validated} 会验证 groups = Group1.class 和 groups未指定的校验注解
     * 因为 {@link Group1} 继承了 {@link Default}，所以会验证 groups 未指定的注解
     * 如果 {@link Group1} 未继承 {@link Default}，则不会验证 groups 未指定的注解
     *
     * @param dto
     * @return
     */
    @PostMapping("/group1")
    public Object validGroup1(@Validated({Group1.class}) @RequestBody ValidGroupDto dto) {
        return dto;
    }

    @PostMapping("/group2")
    public Object validGroup2(@Validated(Group2.class) @RequestBody ValidGroupDto dto) {
        return dto;
    }

    @PostMapping("/group12")
    public Object validGroup12(@Validated({Group1.class, Group2.class}) @RequestBody ValidGroupDto dto) {
        return dto;
    }
}
